package com.dc.web.controller;


import com.dc.constant.MessageConstant;
import com.dc.dao.*;
import com.dc.entity.*;
import com.dc.exception.ServiceException;
import com.dc.model.AjaxResult;
import com.dc.model.WorkflowListBody;
import com.dc.service.CalibrationService;
import com.dc.service.dto.CalibrationHouseSandDto;
import com.dc.service.dto.CalibrationPaintHouseDto;
import com.dc.utils.DateUtils;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Api(tags = "7-1-打砂除锈-打砂房分段打砂-单船")
@RequestMapping("/api/workflow_house_sand")
@RestController
public class WorkflowHouseSandController {

    @Resource
    WorkflowHouseSandDao workflowHouseSandDao;

    @Resource
    WorkflowHouseSandChildDao workflowHouseSandChildDao;

    @Resource
    ShipRepairDao shipRepairDao;

    @Resource
    ShipDao shipDao;

    @Resource
    CalibrationService calibrationService;

    @GetMapping("/list")
    public AjaxResult list(WorkflowListBody body) {

        Integer pageNumber = body.getPageNumber();
        pageNumber = ObjectUtils.defaultIfNull(pageNumber, 1);
        Integer pageSize = body.getPageSize();
        pageSize = ObjectUtils.defaultIfNull(pageSize, 20);

        PageRequest pageRequest = PageRequest.of(pageNumber - 1, pageSize);

        Long repairId = body.getRepairId();     // 维修工单id

        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(repairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }

        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Long shipId = shipRepairEntity.getShipId();
        Optional<ShipEntity> optionalShip = shipDao.findById(shipId);
        if(!optionalShip.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
        }

        ShipEntity shipEntity = optionalShip.get();

        Page<WorkflowHouseSandEntity> resultList = workflowHouseSandDao.findByShipRepairEntity(shipRepairEntity, pageRequest);

        CalibrationHouseSandDto calibrationHouseSandDto = calibrationService.calcHouseSand();

        resultList.getContent().forEach(t -> {
            dynamicCalc(t, shipEntity, shipRepairEntity, calibrationHouseSandDto);
        });

        return AjaxResult.success(resultList);
    }

    @GetMapping("/{id}")
    public AjaxResult show(@PathVariable("id") Long id) {

        Optional<WorkflowHouseSandEntity> optional = workflowHouseSandDao.findById(id);
        if(!optional.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_WORK_FLOW_MISSING);
        }

        WorkflowHouseSandEntity shipOilEntity = optional.get();

        ShipRepairEntity shipRepairEntity = shipOilEntity.getShipRepairEntity();

        Long shipId = shipRepairEntity.getShipId();
        Optional<ShipEntity> optionalShip = shipDao.findById(shipId);

        if(!optionalShip.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
        }

        ShipEntity shipEntity = optionalShip.get();

        CalibrationHouseSandDto calibrationHouseSandDto = calibrationService.calcHouseSand();

        dynamicCalc(shipOilEntity, shipEntity, shipRepairEntity, calibrationHouseSandDto);

        return AjaxResult.success(shipOilEntity);
    }


    //  shipRepairId   weight   shipWeight    submit_time
    @PostMapping()
    public AjaxResult add(@RequestHeader HttpHeaders httpHeaders, @RequestBody WorkflowHouseSandEntity entity) {

        entity.setId(null);

        Long shipRepairId = entity.getShipRepairId();
        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(shipRepairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }

        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Long shipId = shipRepairEntity.getShipId();
        Optional<ShipEntity> optionalShip = shipDao.findById(shipId);
        if(!optionalShip.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
        }

        ShipEntity shipEntity = optionalShip.get();

        entity.setShipRepairEntity(shipRepairEntity);
        entity.setSubmitTime(new Date());

        WorkflowHouseSandEntity save = workflowHouseSandDao.save(entity);

        CalibrationHouseSandDto calibrationPaintHouseDto = calibrationService.calcHouseSand();

        dynamicCalc(save, shipEntity, shipRepairEntity, calibrationPaintHouseDto);

        return AjaxResult.success(save);
    }

    @PutMapping("/{id}")
    public AjaxResult update(@PathVariable("id") Long id, @RequestBody WorkflowPaintHouseEntity entity) {

        Optional<WorkflowHouseSandEntity> optionalPaintHouse = workflowHouseSandDao.findById(id);
        if(!optionalPaintHouse.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_WORK_FLOW_MISSING);
        }

        WorkflowHouseSandEntity houseEntity = optionalPaintHouse.get();

        ShipRepairEntity shipRepairEntity = houseEntity.getShipRepairEntity();

        Long shipId = shipRepairEntity.getShipId();
        Optional<ShipEntity> optionalShip = shipDao.findById(shipId);
        if(!optionalShip.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
        }

        ShipEntity shipEntity = optionalShip.get();

        //////////////////////// 设置字段
        houseEntity.setProject(entity.getProject());
        houseEntity.setArea(entity.getArea());
        houseEntity.setRoom(entity.getRoom());
        houseEntity.setSubmitTime(new Date());

        WorkflowHouseSandEntity save = workflowHouseSandDao.save(houseEntity);

        CalibrationHouseSandDto calibrationPaintHouseDto = calibrationService.calcHouseSand();

        dynamicCalc(save, shipEntity, shipRepairEntity, calibrationPaintHouseDto);

        return AjaxResult.success(save);
    }

    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {

        workflowHouseSandDao.deleteById(id);

        return AjaxResult.success();
    }

    /////////////////////////////////////////////////// child
    @GetMapping("/child/{id}")
    public AjaxResult showChild(@PathVariable("id") Long id) {
        Optional<WorkflowHouseSandChildEntity> optional = workflowHouseSandChildDao.findById(id);
        if(!optional.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_WORK_FLOW_MISSING);
        }

        WorkflowHouseSandChildEntity houseChildEntity = optional.get();

        houseChildEntity.setPid(houseChildEntity.getWorkflowHouseSandEntity().getId());

        return AjaxResult.success(houseChildEntity);
    }

    @PostMapping("/child")
    public AjaxResult addChild(@RequestBody WorkflowHouseSandChildEntity entity) {

        entity.setId(null); // 新增保证 id = null，避免变成更新

        Optional<WorkflowHouseSandEntity> optionalPainHouse = workflowHouseSandDao.findById(entity.getPid());
        if(!optionalPainHouse.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_WORK_FLOW_MISSING);
        }

        WorkflowHouseSandEntity houseEntity = optionalPainHouse.get();

        entity.setWorkflowHouseSandEntity(houseEntity);
        // 动态计算子
        calcChild(entity);

        WorkflowHouseSandChildEntity save = workflowHouseSandChildDao.save(entity);

        return AjaxResult.success(save);
    }

    @PutMapping("/child/{id}")
    public AjaxResult updateChild(@PathVariable("id") Long id, @RequestBody WorkflowHouseSandChildEntity entity) {

        entity.setId(id); // 新增保证 id = null，避免变成更新

        Optional<WorkflowHouseSandEntity> optionalPainHouse = workflowHouseSandDao.findById(entity.getPid());
        if(!optionalPainHouse.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_WORK_FLOW_MISSING);
        }

        WorkflowHouseSandEntity houseEntity = optionalPainHouse.get();

        entity.setWorkflowHouseSandEntity(houseEntity);
        // 动态计算子
        calcChild(entity);

        WorkflowHouseSandChildEntity save = workflowHouseSandChildDao.save(entity);

        save.setPid(houseEntity.getId());

        return AjaxResult.success(save);
    }

    @DeleteMapping("/child/{id}")
    public AjaxResult deleteChild(@PathVariable("id") Long id) {
        Optional<WorkflowHouseSandChildEntity> childEntityOptional = workflowHouseSandChildDao.findById(id);
        if(!childEntityOptional.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_CALIBRATION_MISSION);
        }

        WorkflowHouseSandChildEntity childEntity = childEntityOptional.get();

        WorkflowHouseSandEntity workflowHouseSandEntity = childEntity.getWorkflowHouseSandEntity();
        workflowHouseSandEntity.getInner().remove(childEntity);

        workflowHouseSandDao.save(workflowHouseSandEntity);


        workflowHouseSandChildDao.deleteById(id);

        return AjaxResult.success();
    }

    /////////////////////////////////////////////////  动态计算

    /**
     * 计算动态值
     * @param entity
     * @param shipEntity
     * @param shipRepairEntity
     */

    public static WorkflowHouseSandEntity dynamicCalc(WorkflowHouseSandEntity entity,
                                                ShipEntity shipEntity,
                                                ShipRepairEntity shipRepairEntity,
                                                CalibrationHouseSandDto calibrationHouseSandDto) {

        Double houseSandAirByUnit = calibrationHouseSandDto.getHouseSandAirByUnit();


        // 单位耗压缩空气量标定值
        entity.airByUnit = houseSandAirByUnit;

        // 空气
        entity.air = houseSandAirByUnit * entity.getArea();

        // 总电量， 子表求和
        List<WorkflowHouseSandChildEntity> inner = entity.getInner();
        double sum = inner.stream().mapToDouble(WorkflowHouseSandChildEntity::getTotalPower).sum();

        inner.forEach(t->t.setPid(entity.getId()));

        entity.setPowers(sum);

        ///////////////////////////////////////////////////
        entity.setShipName(shipEntity.getName());
        entity.setReporter(shipRepairEntity.getUpdater());
        entity.setShipRepairId(shipRepairEntity.getId());
        return entity;
    }

    private WorkflowHouseSandChildEntity calcChild(WorkflowHouseSandChildEntity entity) {

        try {
            entity.totalPower = DateUtils.differentDaysDoubleByMillisecond(entity.getStartTime(), entity.getEndTime()) * 24 * entity.getNum() * entity.power;
        } catch (Exception e) {
            entity.totalPower = 0.;
            entity.setPid(entity.getWorkflowHouseSandEntity().getId());
        }
        return entity;
    }
}
